#include "practice_15.10.h"
#include <stdarg.h>
#define DEBUG 

void debug(char *s, ...) {
#ifdef DEBUG
    va_list va;
    va_start(va, s);
    printf("DEBUG:");
    vprintf(s, va);
    va_end(va);
#endif
}

int main(void) {
    struct stat st;   
    int fd, n, status;
    char line[MAXLINE];
    struct timespec req;
    
    if (lstat(FIFO_NAME, &st) < 0) {
        if (errno == ENOENT) {
            if (mkfifo(FIFO_NAME, FILE_MODE))
                err_sys("mkfifo error");
        } else 
            err_sys("lstat error");
    }

    if ((fd= open(FIFO_NAME, O_RDONLY | O_RDWR | O_NONBLOCK)) < 0)
        err_sys("open error");

    status= 0;
    req.tv_sec= 0; 
    req.tv_nsec= NS_PER_MS * 300;
    while (status < 2) {
        debug("status = %d\n", status);
        if ((n= read(fd, line, MAXLINE)) < 0) {
            if (errno== EAGAIN)
                if (status == 0)
                    status++;
                else 
                    ;
            else 
                err_sys("read error");

        } else if (n == 0) {
            if (status == 0)
                debug("waiting client send data...\n");
            else if (status == 1)
                status++;

        } else {
            line[n]= 0;
            printf("get client data: %s\n", line);
        }
        nanosleep(&req, NULL);
    }
    debug("status = %d\n", status);
    return 0;
}
